import React, { useMemo } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Card, SubmitBar, Checkbox } from 'react-vant';
import { ArrowLeft } from '@react-vant/icons';
import axios from 'axios';
import './style/Order.css';

interface OrderItem {
  id: number;
  title: string;
  content: string;
  price: number;
  num: number;
  image: string;
}

export default function Order() {
  const location = useLocation();
  const navigate = useNavigate();
  const cart = location.state as OrderItem[];

  const total = useMemo(() => {
    return cart.reduce((sum, item) => {
      return sum + (item.price / 10) * item.num;
    }, 0);
  }, [cart]);

  // const handlePayment = async () => {
  //   try {
  //     const res = await axios.post('http://localhost:3000/pcpay', { 
  //       payableAmount: total 
  //     });
      
  //     if (res.data.code === 200) {
  //       window.location.href = res.data.result;
  //     }
  //   } catch (error) {
  //     console.error('支付请求失败:', error);
  //   }
  // };

  const handlePayment = async () => {
    try {
      const res = await axios.post('http://localhost:3000/pcpay', { 
        payableAmount: total.toFixed(2) // 确保金额格式正确
      });
      if (res.data.code === 200) {
        // 创建临时容器解析表单
        const formContainer = document.createElement('div');
        formContainer.innerHTML = res.data.result;
        
        // 查找表单并提交
        const form = formContainer.querySelector('form');
        if (form) {
          // 修复可能的表单ID问题
          form.id = 'alipay-payment-form';
          form.name = 'alipay-payment-form';
          
          // 插入表单到页面并提交
          document.body.appendChild(form);
          form.submit();
          
          // 3秒后自动移除表单（防止重复提交）
          setTimeout(() => {
            window.location.href = res.data.res
            document.body.removeChild(form);
          }, 3000);
        } else {
          console.error('解析支付表单失败:', res.data.result);
          alert('支付表单解析失败，请重试');
        }
      }
    } catch (error) {
      console.error('支付请求失败:', error);
      alert('支付请求失败，请检查网络后重试');
    }
  };
  return (
    <div className="order-page">
      <div className="order-header">
        <ArrowLeft onClick={() => navigate(-1)} />
        <h2>确认订单</h2>
      </div>

      <div className="order-content">
        <Card className="order-card">
          <div className="order-items">
            {cart.map((item, index) => (
              <div className="order-item" key={index}>
                <div className="item-image">
                  <img src={item.image} alt={item.title} />
                </div>
                <div className="item-info">
                  <h3 className="item-title">{item.title}</h3>
                  <p className="item-desc">{item.content}</p>
                  <div className="item-price-info">
                    <span className="item-price">¥{(item.price / 10).toFixed(2)}</span>
                    <span className="item-quantity">x{item.num}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card className="order-summary">
          <div className="summary-item">
            <span>商品总价</span>
            <span>¥{total.toFixed(2)}</span>
          </div>
          <div className="summary-item">
            <span>运费</span>
            <span>¥0.00</span>
          </div>
          <div className="summary-item total">
            <span>实付款</span>
            <span className="total-price">¥{total.toFixed(2)}</span>
          </div>
        </Card>
      </div>

      <SubmitBar
        price={(total * 100).toFixed(2)}
        buttonText="立即支付"
        onSubmit={handlePayment}
        className="order-submit"
      />
    </div>
  );
}
